//
//  InsertSort.swift
//  Sorts
//
//  Created by lhc on 2023/12/8.
//

import Foundation



class InsertSort: BaseSort {

    override func sort(action: ((OperatorType, (Int, Int)) -> ())) {
        for i in 1..<self.array.count {
            
            let v = array[i]
            var j = i
            
            while j > 0 && v < array[j - 1] {
                if array[j] != array[j - 1] {
                    action(.assign, (j, array[j - 1]))
                }
                array[j] = array[j - 1]
                j -= 1
            }
            action(.assign, (j, v))
            array[j] = v
        }
    }
}

class InsertExchangeSort: BaseSort {
    
    override func sort(action: ((OperatorType, (Int, Int)) -> ())) {
        
        for i in 1..<array.count {
            
            var j = i
            while j > 0 && array[j - 1] > array[j] {
                action(.exchange, (j - 1, j))
                exchange(a: j - 1, b: j)
                j -= 1
            }
        }
    }
}



